package com.csist.client.task;

import com.csist.model.Message;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

/**
 * @ClassName SendRunnable
 * @Description TODO
 * @Author User
 * @Date 2021/6/14 14:50
 * @ModifyDate 2021/6/14 14:50
 * @Version 1.0
 */
public class ReceiverRunnable implements Runnable{
    private Socket socket;
    private boolean state = true;
    private ObjectInputStream ois = null;
    @Override
    public void run() {
        while (state){
            try {
                ois = new ObjectInputStream(socket.getInputStream());
                Object obj = ois.readObject();
                if (obj instanceof Message){
                    Message message = (Message) obj;
                    if (message.getReceiver()!=0){//服务器发送过来的消息，如果接收者是0代表这是一条群聊消息，否则为私发消息
                        System.out.println("好友消息,"+message.getSendtime()+","+message.getSender()+":"+message.getMsg());
                    } else
                    System.out.println("来自群聊,"+message.getSendtime()+","+message.getSender()+":"+message.getMsg());
                }
            } catch (IOException | ClassNotFoundException e) {
                close();
                e.printStackTrace();
            }
        }
    }

    public ReceiverRunnable(Socket socket) {
        this.socket = socket;
    }
    private void close(){
        this.state = false;
        if (ois!=null) {
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(socket!=null){
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
